<template>
  <div id="app">
    <div class="todo-box">
      <MyHeader :addItem="addItem" />
      <!-- 使用了v-bind单向绑定 -->
      <List :todoList="todoList" :checkTodo="checkTodo" :deleteItem="deleteItem" />
      <MyFooter :todoList="todoList" :checkAllTodo="checkAllTodo" :cancelAllTodo="cancelAllTodo" />
    </div>
  </div>
</template>

<script>
// 引入子组件
import MyHeader from './components/MyHeader.vue'
import List from './components/List.vue'
import MyFooter from './components/MyFooter.vue'
import { nanoid } from 'nanoid'

export default {
  name: 'App',
  components: { MyHeader, List, MyFooter },
  data () {
    return {
      // todoList: [
      //   { id: '001', title: '吃饭', done: false },
      //   { id: '002', title: '睡觉', done: false },
      //   { id: '003', title: '打码', done: true }
      // ]
      todoList: JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods: {
    // 添加一个todo
    addItem (todoObj) {
      console.log('接收到了数据', todoObj);
      this.todoList.push(todoObj)
    },

    // 勾选/取消勾选todo
    checkTodo (id) {
      this.todoList.forEach(todo => {
        if (todo.id === id) return todo.done = !todo.done
      });
    },

    // 删除一个todo
    deleteItem (id) {
      this.todoList = this.todoList.filter(todo => todo.id !== id
      )
    },

    // 全选/全不选
    checkAllTodo (done) {
      this.todoList.forEach(todo => todo.done = done)
    },

    // 删除所有已完成
    cancelAllTodo () {
      this.todoList = this.todoList.filter((todo) => {
        return !todo.done
      })
    }
  },
  watch: {
    todoList: {
      handler (newval, oldval) {
        localStorage.setItem('todos', JSON.stringify(newval))
      },
      deep: true
    }
  }
}
</script>

<style lang="css">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  width: 100%;
  height: 100%;
}

body {
  display: flex;
  width: 100%;
  height: 100%;
}

#app {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.todo-box {
  max-width: 520px;
  width: 70%;
  padding: 10px;
  border: 1px solid #dfdfdf;
  border-radius: 5px;
}
</style>
